package net.betou.trade.admin.action;

import static net.betou.common.page.SimplePage.cpn;
import static net.betou.common.page.SimplePage.cpnPageSize;

import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.betou.common.page.Pagination;
import net.betou.common.util.TradeUtils;
import net.betou.common.web.session.SessionProvider;
import net.betou.trade.action.abs.ActionSupport;
import net.betou.trade.entity.main.AgentAndAdmins;
import net.betou.trade.entity.main.SuggAnswer;
import net.betou.trade.entity.main.Suggestion;
import net.betou.trade.entity.main.SuggestionType;
import net.betou.trade.main.manager.SuggAnswerMng;
import net.betou.trade.main.manager.SuggestionMng;
import net.betou.trade.main.manager.SuggestionTypeMng;
import net.betou.trade.web.Messages;
import net.betou.trade.web.ResponseUtil;
import net.betou.trade.web.WebErrors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;


/**
 * 意见反馈
 * @author O.Y.
 */
@Controller
public class SuggestionAct extends ActionSupport< Suggestion >{
	
	private final Logger log = LoggerFactory.getLogger( this.getClass() );
	
	private final static String QUERY_LIST = "_SUGGESTION_LIST";
	
	@SuppressWarnings("unchecked")
	@RequestMapping( "/suggestion/v_list.jspx" )
	public String toList( Integer pageSize, Integer pageNo, String filterStatus, String searchProperty, String searchValue, String orderProperty, String orderDirection, HttpServletRequest request, HttpServletResponse response, ModelMap model  ){
		
		pageSize = cpnPageSize( pageSize );
		pageNo = cpn( pageNo );
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		Pagination pagination;
		
		pagination = manager.getPage( admin, searchProperty, searchValue, orderProperty, orderDirection, pageNo, pageSize, filterStatus );
		
		HashSet suggIds = buildIds((List<Suggestion>)pagination.getList());
		
		session.setAttribute(request, response, QUERY_LIST, suggIds);
		
		model.addAttribute( "suggestionType", suggestionTypeMng.findList() );
		model.addAttribute( "statusType", Suggestion.getStatusColl() );
		model.addAttribute( "admin", admin );
		paramToModel( model, pagination, null, pageSize, searchProperty, searchValue, orderProperty, orderDirection, filterStatus );
		
		return getListPage( );
	}
	
	private HashSet<Integer> buildIds(List<Suggestion> list){
		HashSet<Integer> suggIds = new HashSet<Integer>();
		if(list!=null){
			for(Suggestion sugg : list){
				suggIds.add(sugg.getId());
			}
		}
		return suggIds;
	}
	
	@RequestMapping( "/suggestion/v_add.jspx" )
	public String v_add( HttpServletRequest request, ModelMap model ){
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		log.debug(admin.getUsername());
		model.addAttribute( "admin", admin );
		model.addAttribute( "suggestionType", suggestionTypeMng.findList() );
		return getAddPage( );
	}
	
	@RequestMapping( "/suggestion/o_save.jspx" )
	public String o_save( Suggestion bean, Integer typeId, String[] filepath, HttpServletRequest request, HttpServletResponse response, ModelMap model ){
		
		WebErrors errors = validateSave( bean );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		log.info(String.valueOf(typeId));
		log.info(String.valueOf(filepath));
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		SuggestionType st = suggestionTypeMng.findById(typeId);
//		log.info(String.valueOf(st));
		if(filepath!=null){
			if(filepath.length>0){
				bean.setFilePath1(filepath[0]);
			}
			if(filepath.length>1){
				bean.setFilePath2(filepath[1]);
			}
			if(filepath.length>2){
				bean.setFilePath3(filepath[2]);
			}
		}
		bean.setAddIp(request.getRemoteAddr());
		
		bean = manager.save( bean, admin, st);
		
		logMng.operating( 0, request, Messages.LOG_SUGGESTION, "id=" + bean.getId( ) + ",title=" + bean.getTitle( ) );
		
		return "redirect:v_list.jspx";
	}
	
	@RequestMapping ( "/suggestion/v_edit.jspx" )
	public String v_edit( Integer id, HttpServletRequest request, ModelMap model ){

		WebErrors errors = validateUpdate( request, id );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		Suggestion bean = manager.findById( id );
		
		model.addAttribute( "bean", bean );
		
		List<SuggAnswer> answerList = suggAnswerMng.findOnSugg(id);
		
		model.addAttribute( "answerList", answerList );
		
		if(bean.getStatus()==1 || bean.getAdmin().equals(admin)){
			model.addAttribute( "readOnly", true );
		}else{
			model.addAttribute( "statusType", Suggestion.getStatusColl() );
			model.addAttribute( "readOnly", false );
		}
		
		return getUpdatePage( );
	}
	
	@RequestMapping ( "/suggestion/o_answer.jspx" )
	public String o_answer(  Integer id, Suggestion bean, SuggAnswer answer, String[] filepath, HttpServletRequest request, ModelMap model ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		WebErrors errors = validateOAnswer( id, bean, answer, admin, request );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		answer.setAddDate(new Date());
		answer.setAddIp(request.getRemoteAddr());
		answer.setSugg(bean);
		if(filepath!=null){
			if(filepath.length>0){
				answer.setFilePath1(filepath[0]);
			}
			if(filepath.length>1){
				answer.setFilePath2(filepath[1]);
			}
			if(filepath.length>2){
				answer.setFilePath3(filepath[2]);
			}
		}
		suggAnswerMng.save(answer, admin);
		
		bean = manager.updateStatus( bean );
		
		logMng.operating( 0, request, Messages.LOG_SUGG_ANSWER, "意见id=" + bean.getId( ) + ",title=" + bean.getTitle( ) + " 反馈id="+answer.getId());
		
		return "redirect:v_list.jspx";
	}
	
	@RequestMapping( "/suggestion/o_delete.jspx" )
	public void o_delete( Integer [ ] ids, HttpServletResponse response, HttpServletRequest request ){
		
		ResponseUtil util = validateDelete( ids, response, request );

		if( util.hasResponse( ) ){
			util.renderJson( );
			return;
		}
		
		suggAnswerMng.deleteBySuggIds(ids);

		Suggestion[ ] beans = manager.deleteByIds( ids );

		for ( Suggestion bean : beans ){
			logMng.operating( 2, request, Messages.LOG_SUGGESTION, "id=" + bean.getId( ) + ",title=" + bean.getTitle( ));
		}

		util.addSuccessResponse( Messages.getDeleteSuccessMessage( beans.length ) );

		util.renderJson( );
		return;
		
	}
	
	private ResponseUtil validateDelete( Integer [ ] ids , HttpServletResponse response, HttpServletRequest request ) {
		ResponseUtil util = ResponseUtil.create( response );

		if( ids == null || ids.length == 0 ){
			util.addErrorResponse( Messages.DATA_NOT_SELECT );
			return util;
		}
		
		HashSet<Integer> hashIds = (HashSet<Integer>)session.getAttribute(request, QUERY_LIST);

		for ( Integer id : ids ){
			Suggestion bean = manager.findById(id);
			if( bean == null ){
				util.addErrorResponse( Messages.DATA_NOT_EXIST );
				break;
			}
			if(!hashIds.contains(id)){
				util.addErrorResponse( Messages.DATA_NOT_OPERATING );
				break;
			}
		}
		return util;
	}
	
	private WebErrors validateOAnswer( Integer id, Suggestion sugg, SuggAnswer answer, AgentAndAdmins admin, HttpServletRequest request ){
		WebErrors errors = WebErrors.create( );
		
		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		HashSet<Integer> ids = (HashSet<Integer>)session.getAttribute(request, QUERY_LIST);
		if(!ids.contains(id)){
			errors.addError( Messages.DATA_NOT_OPERATING );
			return errors;
		}
		
		Suggestion bean = manager.findById(id);
		
		if( bean == null ){
			errors.addError( Messages.DATA_NOT_OPERATING );
			return errors;
		}
		
		if( bean.getStatus()==1 ){
			errors.addError( "意见已处理完成，不必再回复" );
		}
		
		if(bean.getAdmin().equals(admin)){
			errors.addError( "不能对自己的意见进行回复" );
		}
		
		if( sugg.getStatusName().length()==0 ){
			errors.addError( "状态设置不正确" );
		}
		
		if (answer.getContent()==null || answer.getContent().length()==0){
			errors.addError( "回复内容不能为空" );
		}
		
		return errors;
		
	}
	
	private WebErrors validateUpdate( HttpServletRequest request, Integer id ){
		WebErrors errors = WebErrors.create( );
		
		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		HashSet<Integer> ids = (HashSet<Integer>)session.getAttribute(request, QUERY_LIST);
		if(!ids.contains(id)){
			errors.addError( Messages.DATA_NOT_OPERATING );
			return errors;
		}
		
		Suggestion bean = manager.findById( id );
		
		if( bean == null ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		return errors;
			
	}
	
	private WebErrors validateSave( Suggestion bean ){
		WebErrors errors = WebErrors.create( );
		return errors;
	}
	
	@Autowired
	private SessionProvider session;

	@Autowired
	protected SuggestionMng manager;
	
	@Autowired
	protected SuggestionTypeMng suggestionTypeMng;
	
	@Autowired
	protected SuggAnswerMng suggAnswerMng;

	private static final String DIRECTORY = "suggestion";
	@Override
	protected String getDirectory() {
		return DIRECTORY;
	}

}
